import wmi,gevent,subprocess,time
# from gevent.queue import Queue
import threading
from gevent import monkey
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import multiprocessing 
from multiprocessing import Process, Queue

# monkey;monkey.patch_all() 
monkey.patch_all(thread=False, socket=False, select=False)

list = []
ip_list = []
tasks = []

for i in range (2,255):
    if i == 189:
        pass
    else:
        ip_list.append ('172.25.1.{}'.format (i))
        
def ping_ip (ip):
    # start_time = time.time ()
    res = subprocess.call ('ping -n 1 -w 5 %s' % ip,stdout=subprocess.PIPE) # windows 
    if res == False:
        tasks.append (ip)
        # try:
            # wmi_obj = wmi.WMI (computer = ip,user = r'.\admin',password = '2018.pw.')
            # if wmi_obj:
                # tasks.put_nowait (wmi_obj)
                # print ('-->耗时{:.2f}'.format(time.time() - start_time))
        # except:
            # pass
            
def collect (ip):
    # while not tasks.empty ():
        # ip = tasks.get ()
    try:
        # start_time = time.time ()
        wmi_obj = wmi.WMI (computer = ip,user = r'.\admin',password = '2018.pw.')
        if wmi_obj:
            data = {
                        'os_name':wmi_obj.Win32_ComputerSystem()[0].Name, # 显示系统名称 'SIT-I44987-O'
                        'os_system':wmi_obj.Win32_OperatingSystem()[0].Name [:24], # 显示操作系统 'Microsoft Windows 10
                        }
            # print (wmi_obj)
            data.update (get_cpu_info (wmi_obj))
            return data
            # print ('耗时{:.2f}'.format(time.time() - start_time))
    except:
        pass
        
def get_cpu_info (wmi_obj):
    """
    获取CPU的相关数据，这里只采集了三个数据，实际有更多，请自行选择需要的数据
    :return:
    """
    data = {}
    cpu_lists = wmi_obj.Win32_Processor()
    cpu_core_count = 0 
    for cpu in cpu_lists:
        cpu_core_count += cpu.NumberOfCores
        
    cpu_model = cpu_lists[0].Name # CPU型号（所有的CPU型号都是一样的）
    data ['cpu_cont'] = len (cpu_lists)  # CPU个数
    data ['cpu_model'] = cpu_model
    data ['cpu_core_count'] = cpu_core_count # CPU总的核数
    return data
    
if __name__ == '__main__':
    start_time = time.time ()
    task = [gevent.spawn (ping_ip,ip) for ip in ip_list]
    gevent.joinall (task)
    # print (tasks)
    
    cpu_count = multiprocessing.cpu_count()
    print('Cpu count:', cpu_count) # 当前电脑CPU个数
    pool = multiprocessing.Pool(60) # 开启最大进程，53秒左右,max_workers = (os.cpu_count() or 1) * 5
    data = pool.map(collect,[ip for ip in tasks])
    pool.close()
    pool.join()
    # print (data)

    print ('协程执行-->耗时{:.2f}'.format(time.time() - start_time))